package com.wnxy.sddfp.search.service.impl;

import com.wnxy.sddfp.common.model.query.Pages;
import com.wnxy.sddfp.search.model.query.BorrowRecordSearchQuery;
import com.wnxy.sddfp.search.service.SearchService;
import com.wnxy.sddfp.search.vo.BorrowRecordIndexVo;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Pages<BorrowRecordIndexVo> search(BorrowRecordSearchQuery query) {
        // 条件构造器
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        // 条件查询:name
        if (StringUtils.hasText(query.getName())) {
            builder.withQuery(QueryBuilders.matchQuery("name", query.getName()));
        }
        // 条件查询:借款期限
        if (query.getStartPeriod() != null) {
            builder.withQuery(QueryBuilders.rangeQuery("period").gte(query.getStartPeriod()));
        }
        if (query.getStartPeriod() != null) {
            builder.withQuery(QueryBuilders.rangeQuery("period").lte(query.getEndPeriod()));
        }

        // 条件查询:描述
        if (StringUtils.hasText(query.getDescription())) {
            builder.withQuery(QueryBuilders.matchQuery("description", query.getDescription()));
        }
        // 条件查询:分页
        builder.withPageable(PageRequest.of(query.getPageNo() - 1, query.getPageSize()));

        // 条件查询:排序
        builder.withSort(SortBuilders.fieldSort("createdate").order(SortOrder.DESC));
        // 执行搜索ị絶
        SearchHits<BorrowRecordIndexVo> searchHits =
                elasticsearchRestTemplate.search(builder.build(), BorrowRecordIndexVo.class);
        Long totalHits = searchHits.getTotalHits();
        List<SearchHit<BorrowRecordIndexVo>> hitList = searchHits.getSearchHits();

        List<BorrowRecordIndexVo> list =
                hitList.stream().map(SearchHit::getContent).collect(Collectors.toList());
        // 返回
        Pages<BorrowRecordIndexVo> pages = new Pages<>();
        pages.setList(list);
        pages.setTotal(totalHits);
        pages.setPageNum(query.getPageNo());
        pages.setPageSize(query.getPageSize());
        return pages;

    }


}